<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>函数的防抖</title>
    <style>
      .area {
        margin: 20px auto;
        width: 600px;
        height: 300px;
        background-color: brown;
        line-height: 200px;
        font-size: 20px;
        color: #fff;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <div id="normal" class="area"></div>
    <div id="debounce" class="area"></div>
    <div id="throttle" class="area"></div>
    <script>
      const normal = document.querySelector("#normal")
      let normalCount = 0
      normal.onmousemove = function (event) {
        event.target.innerText = `常规模式：鼠标滑动了${normalCount}次`
        normalCount++
      }
      const debounce = document.querySelector("#debounce")
      let debounceCount = 0
      debounce.onmousemove = function (event) {
        // 把之前的定时器清空
        clearTimeout(this.timerId) // 这里只会对500毫秒之内进来的逻辑产生影响
        //   开启定时器
        this.timerId = setTimeout(() => {
          // 500毫秒之后 已经执行完了
          event.target.innerText = `防抖模式：鼠标滑动了${debounceCount}次`
          debounceCount++
        }, 500)
      }

      const throttle = document.querySelector("#throttle")
      throttleCount = 0
      throttle.onmousemove = function (event) {
        // 节流 保证500当前的逻辑 只要开始了计时 就可以执行，如果在500毫秒之内进来 就不执行
        if (!this.timerId) {
          // 如果它存在 表示已经开启了定时器 等待它执行完毕
          this.timerId = setTimeout(() => {
            event.target.innerText = `节流模式：鼠标滑动了${throttleCount}次`
            throttleCount++
            this.timerId = null // 500毫秒之后 自动设置成 空
          }, 500)
        }
      }
    </script>
  </body>
</html>
